<template>
  <div class="main">
    <section>
      <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="right" label-width="120px">
        <el-row :gutter="50">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="用户手机号:" prop="mobile">
              <el-input @keyup.enter.native="search" v-model="listQuery.mobile" placeholder="用户手机号" maxlength="50" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="用户姓名:" prop="realName">
              <el-input @keyup.enter.native="search" v-model="listQuery.realName" placeholder="用户姓名" maxlength="50" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="" class="btn-item">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
          <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
        </el-form-item>
      </el-form>
      <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
        <el-table-column align="center" label="序号" type="index" width="50" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="用户姓名" prop="realName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="用户手机号" prop="mobile" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="用户昵称" prop="nickname"></el-table-column>
        <el-table-column align="center" label="云仓活动名称" prop="seriesName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="商品名称" prop="goodsName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="云仓库存数量" prop="stockNumber" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="下级申购数量" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" @click="orderDetail(scope.row, 2)">{{scope.row.applyedStockNumber}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="160" v-if="rightsButtons['details'] || rightsButtons['inventory']">
          <template slot-scope="scope">
            <el-button type="text" @click="orderDetail(scope.row, 1)" v-if="rightsButtons['details']">下单明细 </el-button>
            <el-button type="text" @click="maintainInventory(scope.row)" v-if="rightsButtons['inventory']">维护库存</el-button>
            <el-button type="text" @click="changeInventory(scope.row)" v-if="rightsButtons['change']">库存转换记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal">
      </el-pagination>
    </section>
    <!-- 操作记录弹窗列表 -->
    <el-dialog title="操作记录" :visible.sync="logoDialog" width="60%">
      <el-table :data="logoList" border highlight-current-row>
        <el-table-column label="序号" prop="sortNo" width="50"></el-table-column>
        <el-table-column label="用户姓名" prop="realName" align="center"></el-table-column>
        <el-table-column label="用户手机号" prop="mobile" align="center"></el-table-column>
        <el-table-column label="用户昵称" prop="nickname" align="center"></el-table-column>
        <el-table-column label="操作人手机号" prop="operateMobile" align="center"></el-table-column>
        <el-table-column label="操作方式" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.operateType===1">添加</span>
            <span v-else-if="scope.row.operateType===2">扣减</span>
            <span v-else-if="scope.row.operateType===3">退货返还库存</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="goodsNumber" align="center"></el-table-column>
        <el-table-column label="财务审批单号" prop="financeNo" align="center"></el-table-column>
        <el-table-column label="维护前库存" prop="oldStockNumber" align="center"></el-table-column>
        <el-table-column label="维护后库存" prop="newStockNumber" align="center"></el-table-column>
        <el-table-column label="操作时间" prop="totalPrice" align="center">
          <template slot-scope="scope">
            <span>{{formatDate(scope.row.createdAt, 'YYYY-MM-DD HH:mm:ss')}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleLogoSizeChange"
        @current-change="handleLogoCurrentChange"
        :current-page.sync="logoQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="logoQuery.pageSize"
        background
        style="text-align: center"
        layout="total, sizes, prev, pager, next, jumper"
        :total="logoTotal">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="logoDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 库存转换记录弹窗列表 -->
    <el-dialog title="库存转换记录" :visible.sync="changeDialog" class="change-dialog">
      <el-table :data="changeList" border highlight-current-row>
        <el-table-column label="序号" prop="sortNo" width="60"></el-table-column>
        <el-table-column label="用户手机号" prop="mobile" align="center"></el-table-column>
        <el-table-column label="用户昵称" prop="nickname" align="center"></el-table-column>
        <el-table-column label="云仓活动名称" prop="fromSeriesName" align="center"></el-table-column>
        <el-table-column label="转换数量" prop="fromStockNumber" align="center"></el-table-column>
        <el-table-column label="转换云仓活动名称" align="center" prop="toSeriesName"></el-table-column>
        <el-table-column label="转换比例" align="center" prop="exchangeRate"></el-table-column>
        <el-table-column label="转换云仓活动数量" align="center" prop="toStockNumber"></el-table-column>
        <el-table-column label="转换时间" prop="updatedAt" align="center"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleChangeSizeChange"
        @current-change="handleChangeCurrentChange"
        :current-page.sync="changeQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="changeQuery.pageSize"
        background
        style="text-align: center"
        layout="total, sizes, prev, pager, next, jumper"
        :total="changeListTotal">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 下单明细、下级申购数量弹窗列表 -->
    <el-dialog :title="orderType===1?'下单明细':'下级申购明细'" :visible.sync="detailDialog" width="60%">
      <el-table :data="detailList" border highlight-current-row>
        <el-table-column label="序号" prop="sortNo" width="50"></el-table-column>
        <el-table-column label="用户姓名" prop="realName" align="center"></el-table-column>
        <el-table-column label="用户手机号" prop="mobile" align="center"></el-table-column>
        <el-table-column label="用户昵称" prop="nickname" align="center"></el-table-column>
        <el-table-column label="云仓活动名称" prop="seriesName" align="center"></el-table-column>
        <el-table-column label="商品名称" prop="goodsName" align="center" v-if="orderType===2"></el-table-column>
        <el-table-column label="申购类型" align="center" prop="applyTypeName" v-if="orderType===1"></el-table-column>
        <el-table-column label="申购时间" prop="totalPrice" align="center" v-if="orderType===1">
          <template slot-scope="scope">
            <span>{{formatDate(scope.row.applyTime, 'YYYY-MM-DD HH:mm:ss')}}</span>
          </template>
        </el-table-column>
        <el-table-column label="申购数量" prop="applyStockNumber" align="center"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleDetailSizeChange"
        @current-change="handleDetailCurrentChange"
        :current-page.sync="detailQuery.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="detailQuery.pageSize"
        background
        style="text-align: center"
        layout="total, sizes, prev, pager, next, jumper"
        :total="detailListTotal">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialog = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="维护库存" :visible.sync="dialogInventory" width="30%" @close="handleDialogClose()">
      <div style="text-align: right;margin-top: -30px;">
        <el-button @click="operatorLogo" type="primary">操作记录</el-button>
      </div>
      <el-form :model="inventoryForm" :rules="inventoryRules" ref="inventoryForm" label-width="130px">
        <el-form-item label="" prop="operateType">
          <el-radio-group v-model="inventoryForm.operateType">
            <el-radio :label="1">添加云仓库存数</el-radio>
            <el-radio :label="2">扣减云仓库存数</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="库存维护数量：" prop="goodsNumber">
          <el-input v-model="inventoryForm.goodsNumber" placeholder="请输入库存维护数量"></el-input>
        </el-form-item>
        <el-form-item label="" prop="goodsNumberAgain">
          <el-input v-model="inventoryForm.goodsNumberAgain" placeholder="再次输入库存维护数量确认"></el-input>
        </el-form-item>
        <el-form-item label="财务审批单号：" prop="financeNo">
          <el-input v-model="inventoryForm.financeNo" placeholder="请输入财务审批单号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogInventory = false">取 消</el-button>
        <el-button type="primary" @click="handleInventory('inventoryForm')">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'yuncangQuery',
    data() {
      const validateGoodsNumber = (rule, value, callback) => {
        if (value !== this.inventoryForm.goodsNumber || !value) {
          callback(new Error('库存维护数量两次输入不一致'))
        } else {
          callback()
        }
      }
      return {
        changeDialog: false,
        changeList: [],
        changeQuery: {
          boxStockUserId : '',
          seriesId: '',
          pageIndex: 1,
          pageSize: 10
        },
        changeListLoading: false,
        changeListTotal: 0,
        logoDialog: false,
        logoLoading: false,
        logoQuery: {
          pageIndex: 1,
          pageSize: 10,
          stockUserId: '',
          stockId:''
        },
        logoList: [],
        logoTotal: 0,
        detailListLoading: false,
        detailQuery: {
          applyUserId: '',
          approvalUserId: '',
          pageIndex: 1,
          pageSize: 10
        },
        detailList: [],
        detailListTotal: 0,
        dialogInventory: false,
        inventoryForm: {
          bizNo: '',
          operateType: 1,
          goodsNumber: '',
          goodsNumberAgain: '',
          financeNo: '',
          stockId: ''
        },
        inventoryRules: {
          goodsNumber: [
            { required: true, message: '库存维护数量不能为空', trigger: 'blur' },
            { pattern: /^[1-9]\d*$/, message: '库存数只可为大于0 的正整数', trigger: 'blur'}
          ],
          goodsNumberAgain: [
            { trigger: 'blur', validator: validateGoodsNumber },
            { pattern: /^[1-9]\d*$/, message: '库存数只可为大于0 的正整数', trigger: 'blur'}
          ],
          financeNo: [
            { required: true, message: '财务审批单号不能为空', trigger: 'blur' }
          ]
        },
        detailDialog: false,
        listLoading: false,
        listQuery: {
          mobile: '',
          realName: '',
          pageIndex: 1,
          pageSize: 10
        },
        list: [],
        listTotal: 0,
        orderType: '',
        orderId: '',
        randFlag: true
      }
    },
    created() {
      if (this.$store.getters.cachedViews.length === 0) this.getList()
    },
    activated() {
      this.getList()
    },
    methods: {
      // 维护库存确定操作
      handleInventory (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm(`确认${(this.inventoryForm.operateType===1?'添加':'扣减')}库存${this.inventoryForm.goodsNumber}个`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.randFlag) {
                this.inventoryForm.bizNo = Math.floor(Math.random() * 999999) // 随机6位数
              }
              this.request({
                url: '/bsnl-product/box/stock/operate',
                method: 'post',
                data: {
                  ...this.inventoryForm
                }
              }).then((res) => {
                if (res.code === '000000' || res.code === 200 || res.status === 200) {
                  this.randFlag = true
                  this.dialogInventory = false
                  this.getList()
                } else {
                  this.randFlag = false
                  this.dialogInventory = true
                }
              }).catch(err => {
                console.log(err)
                this.randFlag = false
                this.dialogInventory = false
              })
            }).catch(err => {
              console.log(err)
            })
          } else {
            this.dialogInventory = true
          }
        })
      },
      // 处理维护库存弹窗关闭
      handleDialogClose () {
        this.inventoryForm = {
          bizNo: '',
          operateType: 1,
          goodsNumber: '',
          goodsNumberAgain: '',
          financeNo: ''
        }
        this.$refs['inventoryForm'].clearValidate()
      },
      operatorLogo () {
        this.logoDialog = true
        this.getLogoList()
      },
      // 获取操作记录接口
      getLogoList () {
        this.logoLoading = true
        this.request({
          url: '/bsnl-product/box/stock/operate/list',
          method: 'post',
          data: { ...this.logoQuery }
        }).then(({data, totalCount}) => {
          this.logoList = data
          this.logoTotal = totalCount
          this.logoLoading = false
        }).catch(err => {
          console.log(err);
          this.logoList = []
          this.logoTotal = 0
          this.logoLoading = false
        })
      },
      // 获取库存转换记录接口
      getChangeList () {
        this.changeLoading = true
        this.request({
          url: '/bsnl-product/box/stockExchangeRecord/list',
          method: 'post',
          data: { ...this.changeQuery }
        }).then(({data, total}) => {
          this.changeList = data
          this.changeListTotal = total
          this.changeLoading = false
        }).catch(err => {
          console.log(err);
          this.changeList = []
          this.changeListTotal = 0
          this.changeLoading = false
        })
      },
      // 获取下单详情接口
      getDetailList () {
        this.detailListLoading = true
        if (this.orderType === 2) {
          this.detailQuery.approvalUserId = this.orderId
          this.detailQuery.applyUserId = ''
          this.detailQuery.applyStatus = 1
        } else {
          this.detailQuery.applyUserId = this.orderId
          this.detailQuery.approvalUserId = ''
          this.detailQuery.applyStatus = 2
        }
        this.request({
          url: '/bsnl-product/box/stock/stock-apply/list',
          method: 'post',
          data: { ...this.detailQuery }
        }).then(({data, totalCount}) => {
          this.$set(this, 'detailList', data)
          this.$set(this, 'detailListTotal', totalCount)
          this.detailListLoading = false
        }).catch(err => {
          console.log(err)
          this.$set(this, 'detailList', [])
          this.$set(this, 'detailListTotal', 0)
          this.detailListLoading = false
        })
      },
      // 1-下单单明细和2-查看当前该用户下级提交的待审批的申购单明细
      orderDetail (row, type) {
        this.orderType = type
        this.orderId = row.userId
        this.getDetailList()
        this.detailDialog = true
      },
      // 维护库存
      maintainInventory (row) {
        this.dialogInventory = true
        this.inventoryForm.stockId = row.id
        this.logoQuery.stockUserId = row.userId
        this.logoQuery.stockId = row.id
      },
      // 库存转换记录
      changeInventory (row) {
        this.changeDialog = true
        this.changeQuery.seriesId = row.seriesId
        this.changeQuery.boxStockUserId  = row.userId
        this.getChangeList()
      },
      // 清空搜索条件
      resetForm (formName) {
        this.$nextTick(() => {
          this.$refs[formName].resetFields()
        })
      },
      // 获取列表
      getList() {
        this.listLoading = true;
        this.request({
          url: '/bsnl-product/box/stock/list',
          method: 'post',
          data: { ...this.listQuery }
        }).then(({data, totalCount}) => {
          this.list = data
          this.listTotal = totalCount
          this.listLoading = false
        }).catch(err => {
          console.log(err);
          this.list = []
          this.listTotal = 0
          this.listLoading = false
        })
      },
      search () {
        this.listQuery.pageIndex = 1
        this.getList()
      },
      handleSizeChange (value) {
        this.listQuery.pageSize = value
        this.getList()
      },
      handleCurrentChange(val){
        this.listQuery.pageIndex = val
        this.getList()
      },
      handleDetailSizeChange (value) {
        this.detailQuery.pageSize = value
        this.getDetailList()
      },
      handleDetailCurrentChange(val){
        this.detailQuery.pageIndex = val
        this.getDetailList()
      },
      handleChangeSizeChange (value) {
        this.changeQuery.pageSize = value
        this.getChangeList()
      },
      handleChangeCurrentChange(val){
        this.changeQuery.pageIndex = val
        this.getChangeList()
      },
      handleLogoSizeChange (value) {
        this.logoQuery.pageSize = value
        this.getLogoList()
      },
      handleLogoCurrentChange(val){
        this.logoQuery.pageIndex = val
        this.getLogoList()
      }
    }
  }
</script>
<style lang="scss" scoped>
.change-dialog {
  /deep/ .el-dialog {
    max-width: 900px!important;
  }
}
</style>